package com.red.wood.common.util;

import java.io.File;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Enumeration;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;


public class CommonUtils {
	
	public static String valueOf(Object object){
		String str = StringUtils.trim(String.valueOf(object));
		boolean check = StringUtils.isBlank(str) || StringUtils.equals(str, "null") || StringUtils.equals(str, "undefined");
		return check ? "" : str;
	}
	
	/**
	 * 获取IP:优先拿site-local地址
	 * @return
	 */
    public static InetAddress getLocalHostLANAddress(){
        try {
            InetAddress candidateAddress = null;
            // 遍历所有的网络接口
            for (Enumeration<?> ifaces = NetworkInterface.getNetworkInterfaces(); ifaces.hasMoreElements();) {
                NetworkInterface iface = (NetworkInterface) ifaces.nextElement();
                // 在所有的接口下再遍历IP
                for (Enumeration<?> inetAddrs = iface.getInetAddresses(); inetAddrs.hasMoreElements();) {
                    InetAddress inetAddr = (InetAddress) inetAddrs.nextElement();
                    if (!inetAddr.isLoopbackAddress()) {// 排除loopback类型地址
                        if (inetAddr.isSiteLocalAddress()) {
                            // 如果是site-local地址，就是它了
                            return inetAddr;
                        } else if (candidateAddress == null) {
                            // site-local类型的地址未被发现，先记录候选地址
                            candidateAddress = inetAddr;
                        }
                    }
                }
            }
            if (candidateAddress != null) {
                return candidateAddress;
            }
            // 如果没有发现 non-loopback地址.只能用最次选的方案
            InetAddress jdkSuppliedAddress = InetAddress.getLocalHost();
            if (jdkSuppliedAddress == null) {
                throw new UnknownHostException("The JDK InetAddress.getLocalHost() method unexpectedly returned null.");
            }
            return jdkSuppliedAddress;
        } catch (Exception e) {
            UnknownHostException unknownHostException = new UnknownHostException("Failed to determine LAN address: " + e);
            unknownHostException.initCause(e);
            return null;
        }
    }
    
	/**
	 * 特殊字符校验，防扫描
	 * @param list
	 */
	public static void fieldCheck(List<String[]> list){
		for(String[] str : list){
			if(str.length < 2){
				continue;
			}
			if(str[0].indexOf("'") >= 0 || str[0].indexOf("\"") >= 0){
				throw new RuntimeException("【"+str[1]+"】不能包含单引号和双引号！");
			}
		}
	}
	
	/**
	 * @Description：获取临时路径，excel导出、文件上传、下载路径
	 * @return
	 */
	public static String getDataTempPath(){
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		String path=request.getSession().getServletContext().getRealPath("/data/temp")+File.separator;
		return path;
	}
	
	/**
	 * 获取导入模板
	 * @return
	 */
	public static String getExportTemplate(){
		String templatePath = "";
		try{
			templatePath= new CommonUtils().getClass().getClassLoader().getResource("/exportTemplate").getPath() + File.separator;
		}catch(Exception e){
			//如果是测试的话
			String path= new CommonUtils().getClass().getClassLoader().getResource("").getPath() + File.separator;
			int p = path.lastIndexOf("/");
			p = path.lastIndexOf("/", p-2);
			path = path.substring(0,p)+"/classes/exportTemplate";
			templatePath = path;
		}
		return templatePath;
	}
	
	/**
	 * IP校验
	 * @param ip
	 * @return
	 */
	public static boolean isValidIp(String ip){
		String reg = "^(\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5])\\."
				+ "(\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5])\\."
				+ "(\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5])\\."
				+ "(\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5])$";
		Pattern pattern = Pattern.compile(reg);
		Matcher p = pattern.matcher(ip);
		return p.matches();
	}
	
	public static boolean isValidDate(String date){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try{
			sdf.setLenient(false);//严格按照给定的格式来校验
			sdf.parse(date);
			return true;
		}catch(Exception e){
			System.out.println(e.getMessage());
			return false;
		}
	}
	
	/**
	 * 转换为Integer类型
	 */
	public static Integer toInteger(Object val){
		return toLong(val).intValue();
	}
	
	/**
	 * 转换为Long类型
	 * @param val
	 * @return
	 */
	public static Long toLong(Object val){
		return toDouble(val).longValue();
	}
	
	/**
	 * 转换为Double类型
	 * @param val
	 * @return
	 */
	public static Double toDouble(Object val){
		if (val == null){
			return -999D;
		}
		try {
			return Double.valueOf(valueOf(val));
		} catch (Exception e) {
			return -999D;
		}
	}
	
	public static byte[] toHexByte(byte[] b){
    	byte[] hexByte=new byte[b.length];
        for (int i = 0; i < b.length; ++i){
        	hexByte[i]=(byte)(b[i]& 0xFF);
        }
        return hexByte;
    }
    public static String toHexString(byte[] b){
        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < b.length; i++){
            buffer.append(toHexString(b[i]));
        }
        return buffer.toString();
    }
    public static String toHexString(byte b){
        String s = Integer.toHexString(b & 0xFF);
        if (s.length() == 1){
            return "0" + s;
        }else{
            return s;
        }
    }
}
